package IO流.对象流;

import java.io.RandomAccessFile;

public class RandomAccessFileDemo {
    public static void main(String[] args) {
        RandomAccessFile raf=null;
        try {
//1. RandomAccessFile(String name,String mode)name 用来确定文件，mode取r(读)rw(可读写)，通过mode可以确定流对文件法访问权限。

            raf=new RandomAccessFile("e:/a.txt","rw");
            //将若干数据写入到文件中
            int[] arr=new int[]{10,20,30,40,50,60,70,80,90};
            for (int i = 0; i < arr.length; i++) {
                raf.writeInt(arr[i]);
            }
            raf.seek(4);//指针  int类型4字节为一个单元
            System.out.println(raf.readInt());
            for (int i = 0; i < 10; i++) {
                raf.seek(4*i);
                System.out.print(raf.readInt()+"\t");
            }
            System.out.println();
            //在第8个字节位置插入一个新的数据45，替换之前的30
            raf.seek(8);
            raf.writeInt(45);
            for (int i = 0; i < arr.length; i++) {
                raf.seek(4*i);
                System.out.print(raf.readInt() + "\t");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (raf!=null){
                    raf.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
